package com.black.framework.aspect;

import cn.hutool.core.util.StrUtil;
import com.black.common.annotation.DeptPremissScope;
import com.black.common.constant.Constants;
import com.black.common.core.domain.entity.SysRole;
import com.black.common.core.domain.resp.AdminUserDetails;
import com.black.common.core.domain.resp.AdminUserResp;
import com.black.common.utils.SecurityUtils;
import com.black.system.domain.req.system.query.SysDeptQueryReq;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 部门权限过滤(sys_role与sys_role_dept表关键)
 *
 * @author
 */
@Log4j2
@Component
@Aspect
public class DeptPremissScopeAspect {

    /**
     * 全部数据权限
     */
    public static final String DATA_SCOPE_ALL = "1";

    /**
     * 自定数据权限
     */
    public static final String DATA_SCOPE_CUSTOM = "2";

    /**
     * 部门数据权限
     */
    public static final String DATA_SCOPE_DEPT = "3";

    /**
     * 部门及以下数据权限
     */
    public static final String DATA_SCOPE_DEPT_AND_CHILD = "4";

    /**
     * 仅本人数据权限
     */
    public static final String DATA_SCOPE_SELF = "5";

    /**
     * 数据权限过滤关键字
     */
    public static final String DATA_SCOPE = "dataScope";

    /**
     * 数据范围过滤
     *
     * @param joinPoint 切点
     * @param user      用户
     * @param deptAlias 部门别名
     * @param userAlias 用户别名
     */
    public static void dataScopeFilter(JoinPoint joinPoint, AdminUserDetails user, String deptAlias, String userAlias) {
        //拼接sql语句的条件用
        StringBuilder sqlString = new StringBuilder();
        // sql条件
        List<String> conditions = new ArrayList<String>();

        //存储当前用户角色的id
        List<String> scopeCustomIds = new ArrayList<String>();

        //得到角色列中的data_scope字段的值
        user.getUser().getRoles().forEach(role -> {
            //如果这里是2，需要拼接sql，查询 sys_role_dept这个表了    select dept_id form sys_role_dept where role_id in (scopeCustomIds数组)
            if (DATA_SCOPE_CUSTOM.equals(role.getDataScope())) {
                scopeCustomIds.add(String.valueOf(role.getRoleId()));
            }
        });

        // 循环遍历角色
        for (SysRole role : user.getUser().getRoles()) {
            // 1,2,3,4,5
            String dataScope = role.getDataScope();
            // 如果已经存在重复的data_scope
            if (conditions.contains(dataScope)) {
                continue;
            }

            // 所有部门权限
            if (DATA_SCOPE_ALL.equals(dataScope)) {
                sqlString = new StringBuilder();
                conditions.add(dataScope);
                break;
            } else if (DATA_SCOPE_CUSTOM.equals(dataScope)) {
                if (scopeCustomIds.size() > 1) {
                    // 多个自定数据权限使用in查询，避免多次拼接。
                    sqlString.append(StrUtil.format(" OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id in ({}) ) ", deptAlias, String.join(",", scopeCustomIds)));
                } else {
                    sqlString.append(StrUtil.format(" OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ", deptAlias, role.getRoleId()));
                }
            } else if (DATA_SCOPE_DEPT.equals(dataScope)) {
                // 本部门权限
                sqlString.append(StrUtil.format(" OR {}.dept_id = {} ", deptAlias, user.getDeptId()));
            } else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)) {
                //部门及以下数据权限  dept_id=102 or  FIND_IN_SET('102',ancestors)
                sqlString.append(StrUtil.format(" OR {}.dept_id IN ( SELECT dept_id FROM sys_dept WHERE dept_id = {} or find_in_set( {} , ancestors ) )", deptAlias, user.getDeptId(), user.getDeptId()));
            } else if (DATA_SCOPE_SELF.equals(dataScope)) {
                //仅本人数据权限
                if (StringUtils.isNotBlank(userAlias)) {
                    sqlString.append(StrUtil.format(" OR {}.user_id = {} ", userAlias, user.getUserId()));
                } else {
                    // 数据权限为仅本人且没有userAlias别名不查询任何数据
                    sqlString.append(StrUtil.format(" OR {}.dept_id = 0 ", deptAlias));
                }
            }
            conditions.add(dataScope);
        }

        // 角色都不包含传递过来的权限字符，这个时候sqlString也会为空，所以要限制一下,不查询任何数据
        if (conditions.isEmpty()) {
            sqlString.append(StrUtil.format(" OR {}.dept_id = 0 ", deptAlias));
        }

        if (StringUtils.isNotBlank(sqlString.toString())) {
            Object params = joinPoint.getArgs()[0];
            if (Objects.nonNull(params) && params instanceof SysDeptQueryReq) {
                SysDeptQueryReq req = (SysDeptQueryReq) params;
                req.setDataScope(" AND (" + sqlString.substring(4) + ")");

                log.info("数据权限动态过滤:{}", req.getDataScope());
            }

        }
    }

    @Before("@annotation(controllerDataScope)")
    public void doBefore(JoinPoint point, DeptPremissScope controllerDataScope) throws Throwable {
        clearDataScope(point);
        handleDataScope(point, controllerDataScope);
    }

    protected void handleDataScope(final JoinPoint joinPoint, DeptPremissScope controllerDataScope) {
        // 获取当前的用户
        AdminUserDetails loginUser = SecurityUtils.getLoginUser();
        if (Objects.nonNull(loginUser)) {
            AdminUserResp currentUser = loginUser.getUser();

            //是不是超级管理员
            boolean isAdmin = currentUser.getRoles().stream().anyMatch(r -> r.getRoleKey().equals(Constants.SUPER_ADMIN));
            // 如果是超级管理员，则不过滤数据
            if (!isAdmin) {
                dataScopeFilter(joinPoint, loginUser, controllerDataScope.deptAlias(),
                        controllerDataScope.userAlias());
            }
        }
    }

    /**
     * 拼接权限sql前先清空params.dataScope参数防止注入
     */
    private void clearDataScope(final JoinPoint joinPoint) {
        Object params = joinPoint.getArgs()[0];
        if (Objects.nonNull(params) && params instanceof SysDeptQueryReq) {
            SysDeptQueryReq req = (SysDeptQueryReq) params;
            req.setDataScope("");
        }
    }
}
